<template>
  <section
    ref="refChart"
    class="chart_wrap"
    :class="className"
    :style="{ height: height, width: width }"
  ></section>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch, nextTick } from "vue";
import * as echarts from "echarts";
import nbGeoJSON from "./GEOJSON/nbGeoJSON.json";

/**
 * 父组件参数
 */
const props = defineProps({
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  chartFontColor: {
    type: String,
    default: "#000",
  },
  autoResize: {
    type: Boolean,
    default: true,
  },
  chartData: {
    type: Object,
    required: true,
  },
  txtFontSize: {
    type: Number,
    default: 15,
  },
});

/**
 * 定义变量
 */
let myChart = null; // 图表
const refChart = ref(null); // 图表ref

/**
 * 监听数据
 */
watch(
  props.chartData,
  (val) => {
    setOption(val);
  },
  { deep: true }
);

/**
 * 方法
 */
/**
 * 工具方法
 */
const setProxyData = (proxyData) => JSON.parse(JSON.stringify(proxyData));

/**
 * 图表相关
 */
// 销毁图表
const destroyChart = (next) => {
  if (myChart) {
    myChart.dispose();
    myChart = null;

    if (next) {
      next();
    }
  }
};
// 重置图表
const resetChart = () => {
  // console.log("初始化图表", myChart)

  destroyChart(() => {
    // 重新启动图表
    initChart();
  });
};
// 初始化图表
const initChart = () => {
  myChart = echarts.init(refChart.value);
  echarts.registerMap("ningbo", nbGeoJSON);
  setOption(props.chartData);
};

const mapData = ref([
  { name: "慈溪市", value: 20057.34 },
  { name: "湾仔", value: 15477.48 },
  { name: "东区", value: 31686.1 },
  { name: "南区", value: 6992.6 },
  { name: "奉化区", value: 44045.49 },
  { name: "深水埗", value: 40689.64 },
  { name: "九龙城", value: 37659.78 },
  { name: "黄大仙", value: 45180.97 },
  { name: "观塘", value: 55204.26 },
  { name: "葵青", value: 21900.9 },
  { name: "荃湾", value: 4918.26 },
  { name: "屯门", value: 5881.84 },
  { name: "元朗", value: 4178.01 },
  { name: "北区", value: 2227.92 },
  { name: "大埔", value: 2180.98 },
  { name: "沙田", value: 9172.94 },
  { name: "西贡", value: 3368 },
  { name: "离岛", value: 806.98 },
]);

let mTime = null;
let dataIndex = 0;

// 地图高亮轮播
const mapActive = (mapData) => {
  if (!myChart) {
    return;
  }
  const dataLength = mapData.length;
  // 用定时器控制高亮
  mTime = setInterval(() => {
    // 清除之前的高亮
    myChart.dispatchAction({
      type: "downplay",
      seriesIndex: 0,
      dataIndex: dataIndex,
    });
    dataIndex++;
    // 当前下标高亮
    myChart.dispatchAction({
      type: "highlight",
      seriesIndex: 0,
      dataIndex: dataIndex,
    });
    myChart.dispatchAction({
      type: "showTip",
      seriesIndex: 0,
      dataIndex: dataIndex,
    });
    if (dataIndex > dataLength) {
      dataIndex = 0;
    }
  }, 3000);
  myChart.on("mouseover", () => {
    console.log("mouseover");
    // 停止定时器，清除之前的高亮
    clearInterval(mTime);
    mTime = "";
    console.log(mTime);
    myChart.dispatchAction({
      type: "downplay",
      seriesIndex: 0,
      dataIndex: dataIndex,
    });
  });
  // 鼠标划出重新定时器开始
  myChart.on("mouseout", () => {
    mapActive(mapData, myChart);
  });
};

// 设置图表
const setOption = ({ fieldData, yData } = {}) => {
  // 绘制图表
  myChart.setOption(
    // ----------------------------  图表配置开始
    {
      /* title: {
        text: "全国主要城市空气质量 - 百度地图",
        subtext: "data from PM25.in",
        sublink: "http://www.pm25.in",
        left: "center",
      }, */
      tooltip: {
        textStyle: {
          fontSize: 18,
        },
        trigger: "item",
        backgroundColor: "rgba(0,0,0,0)",
      },
      geo: {
        type: "map",
        map: "ningbo",
        top: "10%",
        bottom: "10%",
        itemStyle: {
          areaColor: "#2e72bf", // 地图颜色
          borderColor: "#f00", // 省分割线颜色
        },
      },
      legend: {
        bottom: "5%", //图例
        left: "5%", //图例
        itemGap: 20,
        textStyle: {
          color: "#fff",
          padding: [3, 0, 3, 8],
        },
        orient: "vertical", // 图例竖着排列
      },
      /* toolbox: {
        show: true,
        orient: "vertical",
        left: "right",
        top: "center",
        feature: {
          dataView: { readOnly: false },
          restore: {},
          saveAsImage: {},
        },
      }, */
      visualMap: {
        min: 800,
        max: 50000,
        text: ["High", "Low"],
        realtime: false,
        calculable: true,
        inRange: {
          color: ["lightskyblue", "yellow", "orangered"],
        },
      },
      series: [
        {
          type: "map",
          map: "ningbo",
          layoutCenter: ["50%", "50%"],
          layoutSize: "100%",
          data: mapData.value,
          roam: true, // 开启拖拽和缩放
          /* label: {
            show: true,
            color: "#f00",
          }, */
          /* tooltip: {
            // 显示的窗口
            trigger: "item",
            formatter: function (item) {
              var tipHtml = "";
              return tipHtml;
            },
            position: function () {},
            borderWidth: 0,
          }, */
          itemStyle: {
            // 地图样式
            borderColor: "rgba(0, 178, 255, 1)",
            borderWidth: 2,
            // areaColor:'rgba(0, 137, 208, 0.32)',
            areaColor: new echarts.graphic.LinearGradient(
              0,
              1,
              0,
              0,
              [
                { offset: 0, color: "rgba(0, 137, 208, 0.32)" },
                { offset: 1, color: "rgba(0, 66, 164, 0.32)" },
              ],
              false
            ),
            shadowColor: "RGBA(7, 59, 115, .1)",
            shadowOffsetX: -2,
            shadowOffsetY: 2,
            shadowBlur: 10,
          },
          emphasis: {
            // 鼠标移入动态的时候显示的默认样式
            itemStyle: {
              areaColor: "rgba(255, 191, 0, 0.52)",
              borderColor: "rgba(255, 180, 0, 1)",
              borderWidth: 2,
            },
            label: {
              // 文字
              show: true,
              color: "#fff",
              fontSize: 18,
              fontWeight: 600,
              /* formatter: (item) => {
                let html = `{${map[item.data.name].name}|}`;
                return html;
              }, */
              // rich: setEmphasis(),
            },
          },
          label: {
            show: true,
            color: "#fff",
            fontSize: 16,
            fontWeight: 600,
            /* formatter: (item) => {
              let html = `{${map[item.data.name].name}|}`;
              return html;
            }, */
            // rich: setRich(),
          },
          /* geo: {
            map: "温州市",
            type: "map",
            layoutCenter: ["50%", "50%"],
            layoutSize: "150%",
            zoom: 0.65,
            //  aspectScale: 1,
            roam: false,
            label: {
              show: true,
              color: "#fff",
            },
            itemStyle: {
              normal: {
                areaColor: "rgba(0,100,219, 1)",
                shadowColor: "rgba(142, 201, 255, 1)",
                shadowOffsetX: -5,
                shadowOffsetY: 12,
              },
            },
            emphasis: {
              // 鼠标移入动态的时候显示的默认样式
              itemStyle: {
                areaColor: "#019359",
                // borderColor: '#404a59',
                borderWidth: 1,
              },
              label: {
                // 文字
                show: true,
                color: "#fff",
                fontSize: 18,
                fontWeight: 600,
              },
            },
          }, */
        },
      ],
    }
    // ----------------------------  图表配置结束
  );

  // mapActive(mapData.value);
  window.onresize = function () {
    // 自适应大小
    myChart.resize();
  };
};

/**
 * 生命周期
 */
onMounted(() => {
  nextTick(() => {
    initChart(); // 初始化图表
  });
});
onBeforeUnmount(() => {
  destroyChart(); // 销毁图表
});

/**
 * 暴露方法
 */
defineExpose({
  resetChart,
});
</script>

<style lang="scss" scoped>
.chart_wrap {
  min-height: 100px;
}
</style>
